package org.uned.agonzalo16.bitacora.web.user;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.validation.Errors;
import org.uned.agonzalo16.bitacora.dao.UserDao;
import org.uned.agonzalo16.bitacora.domain.User;

@Service
public class ChangePasswordValidator {

	@Autowired
	private UserDao userDao;

	public void validate(ChangePasswordForm form, Errors errors) {
		if (errors.hasErrors()) {
			return;
		}

		User user = userDao.get(form.getId());
		if (user == null) {
			errors.rejectValue("oldPassword", "invalidusername", "invalidusername");
		} else {
			String storedPassword = user.getPassword();
			String currentPassword = DigestUtils.md5DigestAsHex(form.getOldPassword().getBytes());
			if (!currentPassword.equals(storedPassword)) {
				errors.rejectValue("oldPassword", "invalidpassword", "invalidpassword");
			}

			String newPassword = form.getNewPassword();
			String newPasswordAgain = form.getRepeatPassword();
			if (!newPassword.equals(newPasswordAgain)) {
				errors.rejectValue("repeatPassword", "passwordsnotmatch", "passwordsnotmatch");
			}
		}
	}
}
